package com.bestcem.xm.user.grpc.service;

import cn.hutool.core.lang.ObjectId;
import com.bestcem.bp.xm.user.grpc.v1.services.*;
import com.bestcem.xm.common.core.domain.web.RpcStatusResult;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.user.config.properties.SettingProperties;
import com.bestcem.xm.user.service.UserAuthService;
import com.bestcem.xm.user.service.UserService;
import com.bestcem.xm.user.service.dto.user.UserDTO;
import io.grpc.stub.StreamObserver;
import net.devh.boot.grpc.server.service.GrpcService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * 用户中心钉钉相关grpc服务
 *
 * @author panyun <yun.pan@idiaoyan.com>
 * @version v1.0
 * @date 2022/4/1 1:03
 */
@GrpcService
public class UserDingTalkGrpcService extends UserDingTalkServiceGrpc.UserDingTalkServiceImplBase {

    @Resource
    private UserService userService;

    @Resource
    private UserAuthService userAuthService;

    @Autowired
    private SettingProperties settingProperties;

    /**
     * 绑定用户的钉钉信息
     *
     * @param request
     * @param responseObserver
     * @return void
     * @author panyun <yun.pan@idiaoyan.com>
     * @date 2022/4/1 1:05
     */
    @Override
    public void bindDingTalk(BindDingTalkRequest request,
                             StreamObserver<BindDingTalkResponse> responseObserver) {
        BindDingTalkResponse.Builder builder = BindDingTalkResponse.newBuilder();
        String userName = request.getUsername();
        String password = request.getPassword();
        String orgCode = request.getOrgCode();
        String dingUserId = request.getDingUserId();
        String dingUnionid = request.getDingUnionId();
        String dingName = request.getDingName();

        ServiceResult<List<UserDTO>> userByAuth = userAuthService.findUserByAuth(userName, password, orgCode);
        if (userByAuth.isSuccess() && !CollectionUtils.isEmpty(userByAuth.getData())) {
            UserDTO userDTO = userByAuth.getData().get(0);

            UserDTO condition = new UserDTO();
            condition.setOrgId(userDTO.getOrgId())
                    .setDingUserid(dingUserId);
            ServiceResult<List<UserDTO>> oldUser = userService.getUserByCondition(condition);
            if (oldUser.isSuccess() && !CollectionUtils.isEmpty(oldUser.getData())
                    && !userDTO.getUserId().equals(oldUser.getData().get(0).getUserId())) {

                // 清掉旧用户信息
                UserDTO update = new UserDTO();
                update.setUserId(oldUser.getData().get(0).getUserId())
                        .setDingUserid("")
                        .setDingUnionid("")
                        .setDingName("");
                ServiceResult<Integer> updateById = userService.updateById(update);
                if (!updateById.isSuccess() || updateById.getData() != 1) {
                    builder.setStatus(RpcStatusResult.error("清掉旧用户信息失败"));
                    responseObserver.onNext(builder.build());
                    responseObserver.onCompleted();
                }
            }

            // 更新新用户
            UserDTO update = new UserDTO();
            update.setUserId(userDTO.getUserId())
                    .setDingUserid(dingUserId)
                    .setDingUnionid(dingUnionid)
                    .setDingName(dingName);
            ServiceResult<Integer> updateById = userService.updateById(update);
            if (!updateById.isSuccess() || updateById.getData() != 1) {
                builder.setStatus(RpcStatusResult.error("更新新用户失败"));
                responseObserver.onNext(builder.build());
                responseObserver.onCompleted();
            }
        }
        builder.setStatus(RpcStatusResult.success());
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 公司解绑钉钉
     *
     * @param request
     * @param responseObserver
     * @return void
     * @author panyun <yun.pan@idiaoyan.com>
     * @date 2022/4/1 1:05
     */
    @Override
    public void unBindDingTalkByOrgId(UnBindDingTalkByOrgIdRequest request,
                                      StreamObserver<UnBindDingTalkByOrgIdResponse> responseObserver) {
        UnBindDingTalkByOrgIdResponse.Builder builder = UnBindDingTalkByOrgIdResponse.newBuilder();
        String orgId = request.getOrgId();
        if (!ObjectId.isValid(orgId)) {
            builder.setStatus(RpcStatusResult.error("orgId格式不正确"));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        UserDTO userDTO = new UserDTO();
        userDTO.setOrgId(orgId)
                .setDingName("")
                .setDingUserid("")
                .setDingUnionid("");
        ServiceResult<Integer> update = userService.updateByOrgIdSelective(userDTO);
        if (!update.isSuccess() || update.getData() == 0) {
            builder.setStatus(RpcStatusResult.error("公司解绑钉钉失败"));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }
        builder.setStatus(RpcStatusResult.success());
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }
}
